package com.manor.common.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.util.Log
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.bumptech.glide.util.Util
import com.manor.common.R
import com.manor.common.constant.PathConfig
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


@GlideModule
class GlideUtil : AppGlideModule() {
    override fun applyOptions(context: Context, builder: GlideBuilder) {
        super.applyOptions(context, builder)
        /**
         * DiskCacheStrategy.NONE： 表示不缓存任何内容。
         * DiskCacheStrategy.DATA： 表示只缓存原始图片。
         * DiskCacheStrategy.RESOURCE： 表示只缓存转换过后的图片。
         * DiskCacheStrategy.ALL ： 表示既缓存原始图片，也缓存转换过后的图片。
         * DiskCacheStrategy.AUTOMATIC： 表示让Glide根据图片资源智能地选择使用哪一种缓存策略（默认选项）。
         */
        builder.setDefaultRequestOptions(RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE))
        builder.setDefaultRequestOptions(RequestOptions().format(DecodeFormat.PREFER_RGB_565))
        /**
         * 优先外部存储作为磁盘缓存目录，防止内部存储文件过大
         * 外部存储目录默认地址为：/sdcard/Android/data/com.sina.weibolite/cache/image_manager_disk_cache
         */
//设置缓存的大小为100M
        val cacheSize: Long = 100 * 1000 * 1000
        val path: String = PathConfig.getFolderAdapter_Q(PathConfig.FOLDER_NAME_GLIDE_CACHE, false)
        val cache = DiskLruCacheFactory(path, cacheSize)
        builder.setDiskCache(cache)
    }

    override fun isManifestParsingEnabled(): Boolean {
        return false
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
    }
    companion object {
        private val circleRoundDrawableMap: MutableMap<String, CircleRoundDrawable> = mutableMapOf()
//        private fun setPlaceHolder() = R.drawable.default_icon
        /**
         * @param obj
         * @param imageView
         * @describe 与没有context的方法相比 不易导致 内存泄漏问题，原因 activity销毁的时候 imageView 的上下文对象自然不存在
         */
        fun loadImage(
                obj: Any?,
                imageView: ImageView?,
                width: Int = Target.SIZE_ORIGINAL,
                height: Int = Target.SIZE_ORIGINAL,
                needCache: Boolean = true, placeHolder: Int = R.drawable.default_icon
        ) {
            val activity = ActivityManager.getInstance().currentActivity()
            if (null != activity && !activity.isDestroyed){
                var circleRoundDrawable = circleRoundDrawableMap[placeHolder.toString() + ""]
                if (circleRoundDrawable == null) {
                    circleRoundDrawable = CircleRoundDrawable(activity, placeHolder)
                    circleRoundDrawableMap[placeHolder.toString() + ""] = circleRoundDrawable
                }
                circleRoundDrawable.setRoundAngle(0.px)
                Glide.with(activity)
                    .asBitmap()
                    .load(obj)
                    .diskCacheStrategy(if (needCache) DiskCacheStrategy.RESOURCE else DiskCacheStrategy.NONE) // 不使用磁盘缓存
                    .override(width.px, height.px)
                    .error(circleRoundDrawable)
                    .fallback(circleRoundDrawable)
                    .transition(BitmapTransitionOptions.withCrossFade())
                    .dontAnimate()
                    .into(object : SimpleTarget<Bitmap>() {
                        override fun onResourceReady(
                            resource: Bitmap,
                            transition: Transition<in Bitmap>?
                        ) {
                            imageView?.setImageBitmap(resource);
                        }

                        override fun onLoadFailed(errorDrawable: Drawable?) {
                            super.onLoadFailed(errorDrawable)
                        }
                    })
//                    .into(imageView)
            }
        }
        fun loadRoundCorner(
            path: Any?,
            imageView: ImageView,
            width: Int = Target.SIZE_ORIGINAL,
            height: Int = Target.SIZE_ORIGINAL,
            radius: Int = 6,
            type: RoundedCornersTransformation.CornerType = RoundedCornersTransformation.CornerType.ALL,
            isCircle: Boolean = false,
            needCache: Boolean = true, placeHolder: Int = R.drawable.default_icon
        ) {
            val activity = ActivityManager.getInstance().currentActivity()
            if (null != activity && !activity.isDestroyed){
                var circleRoundDrawable = circleRoundDrawableMap[placeHolder.toString() + ""]
                if (circleRoundDrawable == null) {
                    circleRoundDrawable = CircleRoundDrawable(activity, placeHolder)
                    circleRoundDrawableMap[placeHolder.toString() + ""] = circleRoundDrawable
                }
                circleRoundDrawable.setRoundAngle(radius.px)
                if (isCircle){
                    circleRoundDrawable.setType(2)
                }else{
                    circleRoundDrawable.setType(1)
                }

                Glide.with(activity)
                    .load(path)
                    .centerCrop()
                    .transform(CenterCrop(), RoundedCornersTransformation(radius.px, 0.px, type))
                    .transition(DrawableTransitionOptions().crossFade())
                    .override(width.px, height.px)
                    .diskCacheStrategy(if (needCache) DiskCacheStrategy.RESOURCE else DiskCacheStrategy.NONE) // 不使用磁盘缓存
//                .signature(ObjectKey(System.currentTimeMillis()))//通过签名的改变刷新
                    .thumbnail(
                        Glide.with(activity).load(path)
                            .apply(RequestOptions.bitmapTransform(RoundedCorners(radius.px)))
                    )
                    .error(circleRoundDrawable)
                    .fallback(circleRoundDrawable)
                    .placeholder(circleRoundDrawable)
                    .into(imageView)
            }

        }
        /**
         * @describe 清楚内容缓存
         */
        fun clearMemory(context: Context?) {
            Glide.get(context!!).clearMemory()
            System.gc()
        }

        /**
         * @describe 清除磁盘缓存
         */
        fun clearDiskCache() {
            GlobalScope.launch {
                ActivityManager.getInstance().currentActivity()?.let {
                    Glide.get(it).clearDiskCache()
                }
            }
        }

        fun clearViews(context: Context?, view: ImageView?) {
            if (context != null) try {
                if (Util.isOnMainThread()) {
                    Glide.with(context).clear(view!!)
                }
            } catch (e: Exception) {
                Log.e("Glide clear", e.message!!)
            }
        }
    }
}